import service from "./request";
import trim from "lodash/trim";

let cache = {
  url: null,
  params: null,
};

let exp = new Date().getTime();

// 合并 URL 项
// 自动去除多余的 /
const combineUrl = (...urls) => urls.map((url) => trim(url, "/")).join("/");

/**
 * serviceUrl 微服务URL前缀
 */
export default (serviceUrl) => ({
  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Number} wait [重复请求在特定时间内不发出]
   */
  post: (url, params, wait = 1000) => {
    let copy = {
      url,
      params,
    };
    let curTime = new Date().getTime();
    let isStrEq = JSON.stringify(cache) === JSON.stringify(copy);
    let isMatchTime = curTime - exp < wait;
    if (!isStrEq || !isMatchTime) {
      cache = copy;
      exp = curTime;
      return service.post(combineUrl(serviceUrl, url), params);
    }
    return Promise.resolve({ code: "0" });
  },

  /**
   * get方法，对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Number} wait [重复请求在特定时间内不发出]
   */
  get: (url, params, wait = 1000) => {
    let copy = {
      url,
      params,
    };
    let curTime = new Date().getTime();
    let isStrEq = JSON.stringify(cache) === JSON.stringify(copy);
    let isMatchTime = curTime - exp < wait;
    if (!isStrEq || !isMatchTime) {
      cache = copy;
      exp = curTime;
      return service.get(combineUrl(serviceUrl, url), { params });
    }
    return Promise.resolve({ code: "0" });
  },

  /**
   * 上传文件方法
   * @param {String} url 请求的URL地址
   * @param {Form} data 请求的multipart/form-data
   * @returns 请求 Promise
   */
  upload: (url, data) =>
    service.request({
      params: { crm_service_http_type: "upload" },
      url: combineUrl(serviceUrl, url),
      data: data,
    }),

  blobPost: (url, params) =>
    service.post(combineUrl(serviceUrl, url), params, { responseType: "blob" }),

  blobGet: (url, params) =>
    service.get(
      combineUrl(serviceUrl, url),
      { params },
      { responseType: "blob" }
    ),
  /**
   * 下载文件方法
   * @param {String} url 请求的URL地址
   * @param {Form} data 请求的multipart/form-data
   * @returns 请求 Promise
   */
  download: (url, data) => {
    return service.request({
      params: {
        crm_service_http_type: "download",
        ...data,
      },
      url: url,
      // data: data,
      responseType: "blob",
    });
  },
});
